<?php
/**
 * @Author: Marte
 * @Date:   2020-04-04 10:53:45
 * @Last Modified by:   Marte
 * @Last Modified time: 2020-04-04 11:58:38
 */

include_once 'Event.php';
use Tool\Event;         //Event类是php关键字，这里用命名空间作区分

/**
 * 收集事件
 */
function collect(){
    define('EVENT_PATH', 'listener');
    $files = glob(EVENT_PATH . "/*.php");
    if (!empty($files)) {
        foreach ($files as $dir => $fileName) {
            include $fileName;
            $fileName = explode('/',$fileName);
            $className = explode('.',end($fileName))[0];
            if(class_exists($className)){
                $obj = new $className;
                //希望得到自己定义的事件名称,通过反射读取类当中的文档注释
                $re = new \ReflectionClass($obj);
                $str = $re->getDocComment();

                if(strlen($str)<2){
                    throw  new Exception("没有按照规则定义事件名称");
                }else{
                    preg_match("/@Listener\((.*)\)/i",$str,$eventName);
                    if(empty($eventName)){
                        throw  new Exception("没有按照规则定义事件名称");
                    }
                    Event::register($eventName[1],[$obj,'handle']);
                }
            }
        }
    }
}

collect();
Event::trigger('open',['server'=>'server','request'=>'request']);